package com.cust.zy.newtask;

import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;

import com.cust.zy.newtask.activity.TaskActivity;
import com.cust.zy.newtask.activity.TaskListActivity;
import com.cust.zy.newtask.activity.WelcomeScreenActivity;
import com.cust.zy.newtask.dao.DataOperation;
import com.cust.zy.newtask.model.Schedule;
import com.cust.zy.newtask.model.Task;
import com.cust.zy.newtask.model.Word;
import com.cust.zy.newtask.tools.OtherTools;
import com.cust.zy.newtask.tools.TaskResult;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import okhttp3.OkHttpClient;

import static android.R.id.list;

/**
 * Created by zhuangyuan on 4/15/2017.
 */

public class TaskApplication extends Application {
    public static final String TASK_ID_STRING = "TASK_ID_STRING";
    public static final String DB_NAME = "NewTask";
    private DataOperation dataOperation;

    private Task task;
    private Schedule schedule;
    private List<List<Word>> amMap;
    private List<List<Word>> pmMap;

    @Override
    public void onCreate() {
        super.onCreate();
        Stetho.initializeWithDefaults(this);
        new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())
                .build();
        SharedPreferences preferences = this.getSharedPreferences("preferences", MODE_PRIVATE);
        String taskID = preferences.getString("TaskID", "");
        dataOperation = new DataOperation(getApplicationContext());
        if (!taskID.equals("") && taskID != "" && taskID != null&&!taskID.equals("1")) initialData(taskID);
        else{
            Intent intent = new Intent(this, TaskListActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(intent);
        }
    }

    public void initialData(String taskID) {
        GetTaskTask getTaskTask = new GetTaskTask(taskID);
        getTaskTask.execute();
    }


    private class GetTaskTask extends AsyncTask<String, Object, TaskResult<Task>> {
        private String taskID;

        public GetTaskTask(String taskID) {
            this.taskID = taskID;
        }

        @Override
        protected TaskResult<Task> doInBackground(String... arg0) {
            try {
                ArrayList<Task> list = dataOperation.queryTask("ID = ?", new String[]{taskID});
                if (list.size() > 0) return new TaskResult<Task>(list.get(0));
                else return new TaskResult<Task>(new Exception("TaskID is null"));
            } catch (Exception e) {
                return new TaskResult<Task>(e);
            }
        }

        @Override
        protected void onPostExecute(TaskResult<Task> result) {
            if (result.isValid()) {
                task = result.getResult();
                GetSchedule getSchedule = new GetSchedule();
                getSchedule.execute();
            } else {
                result.getException().printStackTrace();
            }
        }
    }

    private class GetSchedule extends AsyncTask<String, Object, TaskResult<Schedule>> {

        @Override
        protected TaskResult<Schedule> doInBackground(String... arg0) {
            try {
                String temp = "";
                Properties props = new Properties();
                int day = OtherTools.getDifferenceBetweenGenerateAndCur(task.getGenerateTime()) + 1;
                props.load(getApplicationContext().getAssets().open("Schedule.properties"));
                temp = props.getProperty("type" + task.getType() + "_" + day);
                Schedule schedule = new Schedule();
                if (temp != null && !temp.equals("") && temp.contains("/")) {
                    String[] am = temp.split("/")[0].split(",");
                    String[] pm = temp.split("/")[1].split(",");
                    schedule.setAm(am);
                    schedule.setPm(pm);
                } else if (temp != null && !temp.equals("") && !temp.contains("/")) {
                    String[] am = temp.split("/")[0].split(",");
                    schedule.setAm(am);
                }
                return new TaskResult<Schedule>(schedule);
            } catch (Exception e) {
                return new TaskResult<Schedule>(e);
            }
        }
        @Override
        protected void onPostExecute(TaskResult<Schedule> result) {
            if (result.isValid()) {
                schedule = result.getResult();
                GetWordTask getWordTask = new GetWordTask();
                getWordTask.execute();
            } else {
                result.getException().printStackTrace();
            }
        }
    }

    private class GetWordTask extends AsyncTask<String, Object, TaskResult<Boolean>> {

        @Override
        protected TaskResult<Boolean> doInBackground(String... arg0) {
            try {
                amMap = new ArrayList<>();
                for(int i = 0;i<schedule.getAm().length;i++){
                    ArrayList<Word> list = dataOperation.queryWord(
                            "TASK_ID = ? and LIST = ?", new String[]{task.getID(),schedule.getAm()[i]});
                    amMap.add(list);
                }

                pmMap = new ArrayList<>();
                for(int i = 0;i<schedule.getPm().length;i++){
                    ArrayList<Word> list = dataOperation.queryWord(
                            "TASK_ID = ? AND LIST = ?", new String[]{task.getID(),schedule.getPm()[i]+""});
                    pmMap.add(list);
                }

                return new TaskResult<Boolean>(true);
            } catch (Exception e) {
                return new TaskResult<Boolean>(e);
            }
        }

        @Override
        protected void onPostExecute(TaskResult<Boolean> result) {
            if (result.isValid()) {
                Intent intent = new Intent(getApplicationContext(), TaskActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
            } else {
                result.getException().printStackTrace();
            }
        }
    }


    public Task getTask() {
        return task;
    }

    public void setTask(Task task) {
        this.task = task;
    }

    public Schedule getSchedule() {
        return schedule;
    }

    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }

    public List<List<Word>> getAmMap() {
        return amMap;
    }

    public void setAmMap(List<List<Word>> amMap) {
        this.amMap = amMap;
    }

    public List<List<Word>> getPmMap() {
        return pmMap;
    }

    public void setPmMap(List<List<Word>> pmMap) {
        this.pmMap = pmMap;
    }
}
